import React, { useEffect, useRef, useState } from 'react';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import { Text, View } from 'native-base';
import { StatusBar, ScrollView, StyleSheet } from 'react-native';
import Header from './component/Header.tsx';
import MerchantInformation from './component/MerchantInformation.tsx';
import ProductIndexScreen from './component/ProductIndexScreen.tsx';
import { NativeSyntheticEvent } from 'react-native/Libraries/Types/CoreEventTypes';
import { NativeScrollEvent } from 'react-native/Libraries/Components/ScrollView/ScrollView';
import { useSelector } from 'react-redux';
import { RootState } from '../../../redux/store.ts';
import HomeRequest from '../../../request/homeRequest.ts';
import { useReactive } from 'ahooks';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import ShoppingCart from '../component/ShoppingCart.tsx';

interface IMerchantProductProps {
  navigation: NavigationProp<any, 'merchantProduct'>;
  route: RouteProp<{ merchantProduct: any }, 'merchantProduct'>;
}

interface IState {
  merchantList: IObtainMerchantListRes[];
  merchantInfo?: IObtainMerchantListRes;
  merchantId: number;
  hasProductListLoading: boolean;
  collect: boolean;
}
interface IMerchantProductContextValue {
  collect: boolean;
  onCollectionChange: (value: boolean) => void;
}
export const MerchantProductContext = React.createContext<IMerchantProductContextValue | null>(null);
const MerchantProduct: React.FC<IMerchantProductProps> = ({ navigation, route }) => {
  const [headerHeight, setHeight] = useState(0);
  const [scrollEnabled, setScrollEnabled] = useState(false);
  const beeperId = useSelector((state: RootState) => state.beeperId);
  const btnInformation = useSelector((state: RootState) => state.btnInformation);
  const beeperParams = useSelector((state: RootState) => state.beeperParams);
  const scrollViewRef = useRef<ScrollView>(null);
  const state = useReactive<IState>({ merchantList: [], merchantId: 0, hasProductListLoading: false, collect: false });

  useEffect(() => {
    fetchObtainMerchantList();
  }, []);

  // 获取商户列表
  const fetchObtainMerchantList = () => {
    Loading.show();
    const params = { type: 1, btnId: btnInformation!.id, beeperId, btnType: btnInformation!.btnType, classifyIds: btnInformation!.classifyIds, ...beeperParams };
    HomeRequest.ObtainMerchantList(params)
      .then((res) => {
        state.merchantList = res.data;
        scrollViewRef.current?.scrollTo({ y: 0, animated: true });
        if (res.data.length > 0) {
          if (state.merchantId) {
            state.merchantInfo = res.data.find((item) => item.id === state.merchantId);
          } else {
            state.merchantId = res.data[0].id;
            state.merchantInfo = res.data[0];
          }
        }
        Loading.hide();
      })
      .catch((err) => {
        // 仅会员能购买
        if (err === '并非该按钮中商户的会员') {
          setTimeout(() => {
            navigation.goBack();
          }, 2000);
        }
        Loading.hide();
      });
  };

  /**
   * 处理滚动事件 判断是否到滚动底部
   * @param event
   */
  const handleScrollEvent = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
    const { contentOffset, layoutMeasurement, contentSize } = event.nativeEvent;
    const isAtBottom = contentOffset.y + layoutMeasurement.height >= contentSize.height - 5;
    setScrollEnabled(isAtBottom);
  };

  /**
   * 商户切换
   * @param activeId
   */
  const handleMerchantChange = (activeId: number) => {
    state.merchantId = activeId;
    state.merchantInfo = undefined;
    state.merchantList = [];
    fetchObtainMerchantList();
  };

  return (
    <MerchantProductContext.Provider value={{ collect: state.collect, onCollectionChange: (value) => (state.collect = value) }}>
      <View bg={'white'} flex={1}>
        <StatusBar translucent backgroundColor={'transparent'} barStyle="dark-content" />
        <Header navigation={navigation} activeId={state.merchantId} merchantList={state.merchantList} onLayout={(height) => setHeight(height + 80)} onMerchantChange={handleMerchantChange} />
        <ScrollView ref={scrollViewRef} scrollEnabled={!scrollEnabled} onScroll={handleScrollEvent}>
          {state.merchantInfo && <MerchantInformation merchantInfo={state.merchantInfo} />}
          <ScrollView horizontal={true} scrollEnabled={false}>
            {state.merchantInfo && <ProductIndexScreen merchantId={state.merchantId} headerHeight={headerHeight} scrollEnabled={scrollEnabled} onProdLoadSuccCB={(result) => (state.hasProductListLoading = result)} />}
          </ScrollView>
        </ScrollView>
        {state.hasProductListLoading && <ShoppingCart />}
      </View>
    </MerchantProductContext.Provider>
  );
};

const styles = StyleSheet.create({
  root: { flex: 1 },
});

export default MerchantProduct;
